package ngat.oss;

import java.rmi.*;
import java.rmi.server.*;
import java.util.*;

/** Basic impleme ntation of ScheduleMonitor.*/
public class DefaultScheduleMonitor extends UnicastRemoteObject implements ScheduleMonitor {

    private List listeners;

    public DefaultScheduleMonitor() throws RemoteException {
	super();
	listeners = new Vector();
    }

    
    /** Add a listener to the list.*/
    public void addScheduleUpdateListener(ScheduleUpdateListener l) throws RemoteException {
	if (! listeners.contains(l))
	    listeners.add(l);
	System.err.println("**DefaultScheduleMonitor.addSUListener(): "+l);
    }
    
    /** Remove a listener from the list.*/
    public void removeScheduleUpdateListener(ScheduleUpdateListener l) throws RemoteException {
	if (listeners.contains(l))
	    listeners.remove(l);
	System.err.println("**DefaultScheduleMonitor.removeSUListener(): "+l);
    }

    public void notifyListenersSweepStarted(long time, int sweepId) throws RemoteException {

	Iterator it = listeners.iterator();
	while (it.hasNext()) {
	    ScheduleUpdateListener l = (ScheduleUpdateListener)it.next();
	    try {
		l.scheduleSweepStarted(time, sweepId);
	    } catch (Exception e) {
		e.printStackTrace();
		it.remove();	
		System.err.println("**WARNING: DefaultScheduleMonitor.notifyListenersSweepStarted(): Removed unresponsive listener: "+l);
	    }
	}
	
    }

    public void notifyListenersRunCompleted(long time, Set metrics)throws RemoteException {

	
	Iterator it = listeners.iterator();
	while (it.hasNext()) {
	    ScheduleUpdateListener l = (ScheduleUpdateListener)it.next();
	    try {
		l.scheduleRunCompleted(time, metrics);
	    } catch (Exception e) {
		e.printStackTrace();
		it.remove();
		System.err.println("**WARNING: DefaultScheduleMonitor.notifyListenersRunCompleted(): Removed unresponsive listener: "+l);
	    }
	}

    }

    /** Notify listeners that server is alive. DEBUG*/
    public void notifyListenersImalive() throws RemoteException {
	
	Iterator it = listeners.iterator();
	while (it.hasNext()) {
	    ScheduleUpdateListener l = (ScheduleUpdateListener)it.next();
	    try {
		l.imalive();
	    } catch (Exception e) {
		e.printStackTrace();
		it.remove();
		System.err.println("**WARNING: DefaultScheduleMonitor.notifyListenersImalive(): Removed unresponsive listener: "+l);
	    }
	}

    }
    

}
